package com.wf.controller;

import com.mysql.cj.log.Log;
import com.wf.dto.TaskDTO;
import com.wf.service.MyService;
import com.wf.vo.Result;
import com.wf.vo.TaskRepresentation;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class MyRestController {

    @Autowired
    private MyService myService;

    @Autowired
    TaskService taskService;

    @RequestMapping(value="/process", method= RequestMethod.POST)
    public void startProcessInstance() {
        myService.startProcess();
    }

    @RequestMapping(value="/tasks", method= RequestMethod.GET, produces= MediaType.APPLICATION_JSON_VALUE)
    public Result getTasks(@RequestParam String assignee) {
        List<Task> tasks = myService.getTasks(assignee);
        List<TaskRepresentation> taskRepresentations = new ArrayList<>();
        for (Task task : tasks) {
            TaskRepresentation taskRepresentation = new TaskRepresentation();
            taskRepresentation.setId(task.getId());
            taskRepresentation.setName(task.getName());
            taskRepresentation.setVariables(taskService.getVariables(task.getId()));
            taskRepresentations.add(taskRepresentation);
        }
        return Result.success(taskRepresentations);
    };

    @PostMapping("/complete")
    public void  completeTask(@RequestBody TaskDTO taskDTO)
    {
        log.info(String.valueOf(taskDTO));

        myService.completeTask(taskDTO);
    }

    @GetMapping("history")
    public Result getHistory(String assignee)
    {

        List<HistoricActivityInstance> history = myService.getHistory(assignee);

        return Result.success(history);

    }


}